<template>
  <div class="app-container">
    <el-form ref="addCouponData" :model="addCouponData"   class="addTictStyle"
             label-position="top">
      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <h3 class="ticTitle">基本信息:</h3>
        </el-col>
      </el-row>
    <el-row :span="24">
      <el-col :span="16" :offset="4">
            <el-form-item label="满减券名称:" prop="name">
              <el-input v-model="addCouponData.name" placeholder="满减劵名称" />
            </el-form-item>
      </el-col>
    </el-row>
      <el-row :span="24">
        <el-col :span="16" :offset="4">
            <el-form-item label="满减劵副标题:" prop="subtitle">
              <el-input v-model="addCouponData.subtitle" placeholder="优惠券副标题" />
            </el-form-item>
          </el-col>
        </el-row>

<!--      <el-row :span="24">-->
<!--        <el-col :span="16" :offset="4">-->
<!--            <el-form-item label="优惠券类型" prop="category">-->
<!--              <el-select-->
<!--                v-model="addCouponData.category"-->
<!--                filterable-->
<!--                placeholder="请选择验证方式"-->
<!--                @change="currentSel"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="typeOption in categoryOption"-->
<!--                  :key="typeOption.name"-->
<!--                  :label="typeOption.name"-->
<!--                  :value="typeOption.name"-->
<!--                >-->
<!--                  {{ typeOption.name }}-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--      </el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item v-if="totalandless" label="满" prop="discount.base">-->
<!--              <el-col :span="8">-->
<!--                <el-input v-model="addCouponData.templateRule.discount.base"-->
<!--                          type='number' />-->
<!--              </el-col>-->
<!--              <el-col class="line" :span="1">减</el-col>-->
<!--              <el-col :span="8">-->
<!--                <el-input v-model="addCouponData.templateRule.discount.quota"-->
<!--                          type='number'/>-->
<!--              </el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item v-if="discount" label="折数" prop="discount.quota">-->
<!--              <el-input v-model="addCouponData.templateRule.discount.quota"-->
<!--                        type='number'/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="发放数量(张)" prop="couponCount">
            <el-input v-model="addCouponData.couponCount"
                      type='number' />
          </el-form-item>
        </el-col>
      </el-row>
<!--        <el-col :span="10">-->
<!--          <el-form-item label="背景" prop="imgStr">-->
<!--            <el-upload-->
<!--              ref="upload"-->
<!--              action="''"-->
<!--              list-type="picture-card"-->
<!--              :file-list="showImgs"-->
<!--              :auto-upload="false"-->
<!--              :http-request="uploadFile"-->
<!--            >-->
<!--              <i class="el-icon-plus" />-->
<!--            </el-upload>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="20">-->
<!--          <el-form-item label="描述" prop="usage">-->
<!--            <el-input v-model="addCouponData.couponDesc" type="textarea" placeholder="规则表述" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->

<!--      </el-col>-->
      <el-row :span="24">
        <el-col :span="16" :offset="4">
            <el-form-item label="使用门槛:" prop="usage">
              <el-radio-group v-model="addCouponData.category" @change="usageShow" style="width:100%">
                <el-form-item style="display:inline-block;margin-right:0px; vertical-align:top;width:230px">
                <el-radio label="0">
                  无门槛
                </el-radio>
                <el-radio label="1">
                  消费金额
                </el-radio>
              </el-form-item>
                <el-form-item style="display:inline-block;margin-right:10px;vertical-align:top;width:calc(100% - 240px);float:right;margin-right: 0px">
                <el-input v-if="tickKindShow" v-model="addCouponData.templateRule.discount.base" style="width:100%" ></el-input>
                </el-form-item>
              </el-radio-group>
            </el-form-item>
        </el-col>
      </el-row>
      <el-row :span="24">
        <el-col :span="16" :offset="4">
      <el-form-item label="优惠券内容:">
          <span style="display:inline-block;margin-right:0px;vertical-align:top;width:110px">减免金额(元)</span>
      <el-input v-model="addCouponData.templateRule.discount.quota" style="display:inline-block;vertical-align:top;width:calc(100% - 110px);float:right;margin-right: 0px"></el-input>
      </el-form-item>
        </el-col>
      </el-row>

      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="适用商品:" prop="usage">
            <el-radio-group v-model="addCouponData.templateRule.usage.usageType" @change="showSelectProducts" style="width:100%">
              <el-form-item style="display:inline-block;margin-right:0px; vertical-align:top;width:230px">
                <el-radio label="0">
                  全部商品
                </el-radio>
                <el-radio label="1">
                  指定商品可用
                  <button v-if="selectProducts">选择商品</button>
                </el-radio>
                <el-radio label="2">
                  指定商品不可用
                  <button v-if="unSelectProducts">选择商品</button>
                </el-radio>
              </el-form-item>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row :span="24"><el-col :sapn="16" :offset="4">
        <h3 class="ticTitle">基本信息:</h3>
      </el-col>
      </el-row>
      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="领取人限制:" prop="usage">
            <el-radio-group v-model="addCouponData.templateRule.receive.receiveType" @change="useLimitation" style="width:100%">
              <el-form-item style="display:inline-block;margin-right:0px; vertical-align:top;width:260px">
              <el-radio label="0">
                所有用户可领
              </el-radio>
              <el-radio label="1">
                指定用户领取
              </el-radio>
              </el-form-item>
              <el-form-item style="display:inline-block;margin-right:10px;vertical-align:top;width:calc(100% - 270px);float:right;margin-right: 0px">
              <el-select
                v-model="addCouponData.templateRule.receive.userType"
                filterable
                placeholder="请选择用户"
                style="width:100%"
                v-if="assignUser"
              >
                <el-option
                  v-for="userApply in userApplyOptions"
                  :key="userApply.code"
                  :label="userApply.name"
                  :value="userApply.code"
                >
                  {{ item.name }}
                </el-option>
              </el-select>
              </el-form-item>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>



      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="每人限领:" prop="usage">
            <el-radio-group v-model="addCouponData.templateRule.limitation.limitationType" @change="defineDaraw" style="width:100%">
              <el-form-item style="display:inline-block;margin-right:0px; vertical-align:top;width:200px">
              <el-radio label="0">
                不限次数
              </el-radio>
              <el-radio label="1">
                限定次数
              </el-radio>
              </el-form-item>
              <el-form-item style="display:inline-block;margin-right:10px;vertical-align:top;width:calc(100% - 210px);float:right;margin-right: 0px">
              <el-input v-if="showDefineCount" v-model="addCouponData.templateRule.limitation.limitation"  style="width:100%" type="number"></el-input>
              </el-form-item>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row :span="24">
        <el-col :span="16" :offset="4">
            <el-form-item label="有效日期:" prop="limitTime">
              <el-radio-group v-model="addCouponData.templateRule.expiration.period" @change="limitTimeShow" style="width:100%">

                <el-form-item label="" prop="effectiveDate">
                  <el-col :span="24">
                  <el-radio label="0" style="width:100%">
                    有效日期
                    <el-time-picker
                      v-if="effectiveShow"
                      v-model="effectiveDate"
                      value-format="timestamp"
                      is-range
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围"
                      style="width:93%"
                    />
                  </el-radio>
                  </el-col>
                </el-form-item>
                  <el-col :span="24">
                  <el-radio label="1" style="width:100%">领取优惠后，当天生效，有效期天数
                    <el-input v-if="getCouponDateShow" v-model="addCouponData.templateRule.expiration.gap"
                              type='number'style="width:77%" />
                  </el-radio>
                  </el-col>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="跳转链接" prop="url">
            <el-input v-model="addCouponData.url" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-footer height="80px">
        <el-row style="display: flex;justify-content: center;align-items: center;">
          <el-button @click="submit" type="primary">
            保存
          </el-button>
          <el-button @click="editOut">
            取消
          </el-button>
        </el-row>
      </el-footer>
    </el-form>
  </div>
</template>

<script>
import { replaceSpacesObj } from '../../../utils/webUtils.js'

export default {
  name: 'AddTict',
  components: {},
  data() {
    return {
      uuid: '',
      addCouponData: {
        id:'',
        name: '',
        subtitle: '',
        category: '',
        categoryName:'',
        businessLine: '',
        businessLineName: '',
        backgroudImg: '',
        distributeTarget: '',
        url: '',
        available: '',
        couponDesc: '',
        couponCount: '',
        templateRule:{
         expiration:{
            period:'',
           gap:'',
           startTime:'',
           endTime:''
          },
          receive:{
            receiveType:'',
            userType:''
          },
        discount:{
          quota:'',
          base:''
        },
        limitation: {limitation:'',limitationType:''},
        usage:{
          usageType:'',
          goodsType:'',
          goodsIds:''
        },
        },
      },
      userApplyOptions:[],
      effectiveDate:'',
      showImgs: [],
      list: [],
      couponData:[],
      validOptions: {},
      yardOptions: [],
      mercList: [],
      merchants: { name: '', uuid: '' },
      tickValue: [],
      validationOptions: [],
      applyUserOption: [],
      applyShowOption: [],
      categoryOption: [],
      selVal: '',
      rules: {},
      info: '',
      infoShow: false,
      imgList: [],
      imgformData: {},
      editBoxShow: false,
      displayDate: false,
      totalandless: false,
      discount: false,
      userShow: false,
      tickKindShow: false,
      getCouponDateShow: false,
      effectiveShow: false,
      assignUser:false,
      showDefineCount:false,
      selectProducts:false,
      unSelectProducts:false

    }
  },
  mounted() {
    this.queryApplyUser()
    this.queryApplyShow()
    this.querycategory()
  },
  methods: {
    // 根据代码获取指定用户
    queryTeamCus() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/TCK_USER',
          params: {}
        })
        .then(response => {
          this.userApplyOptions = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    limitTimeShow() {
      if (this.addCouponData.templateRule.expiration.period == '0') {
        this.effectiveShow = true
        this.getCouponDateShow = false
        this.addCouponData.templateRule.expiration.gap=''
      } else if (this.addCouponData.templateRule.expiration.period == '1') {
        this.effectiveShow = false
        this.getCouponDateShow = true
        this.effectiveDate = ''
      } else {
        this.effectiveShow = false
        this.getCouponDateShow = false
      }
    },
    useLimitation(){
      if (this.addCouponData.templateRule.receive.receiveType == '0') {
        this.assignUser = false
        this.addCouponData.templateRule.receive.userType=''
      } else if (this.addCouponData.templateRule.receive.receiveType == '1') {
        this.assignUser=true
      }
    },
    showSelectProducts(){
      if (this.addCouponData.templateRule.usage.usageType == '1') {
        this.selectProducts = true
        this.unSelectProducts=false
        this.addCouponData.templateRule.usage.goodsIds=''
      } else if (this.addCouponData.templateRule.usage.usageType == '2') {
        this.unSelectProducts=true
        this.selectProducts=false
        this.addCouponData.templateRule.usage.goodsIds=''
      }else{
        this.selectProducts=false
        this.unSelectProducts=false
        this.addCouponData.templateRule.usage.goodsIds=''
        this.addCouponData.templateRule.usage.unGoodsIds=''
      }
    },
    defineDaraw(){
      if (this.addCouponData.templateRule.limitation.limitationType == '0') {
        this.showDefineCount = false
        this.addCouponData.templateRule.limitation.limitation=''
      } else if (this.addCouponData.templateRule.limitation.limitationType == '1') {
        this.showDefineCount=true
      }
    },
    usageShow() {
      if (this.addCouponData.category == '0') {
        this.userShow = true
        this.tickKindShow = false
        this.addCouponData.templateRule.discount=''
      } else if (this.addCouponData.category == '1') {
        this.userShow = false
        this.tickKindShow = true
        this.addCouponData.templateRule.discount.base=''
      } else {
        this.userShow = false
        this.tickKindShow = false
        this.addCouponData.templateRule.usage.discount.base=''
      }
    },
    // currentSel(selVal) {
    //   this.selVal = selVal
    //   console.log(this.selVal == '满减劵')
    //   console.log(this.selVal == '打折劵')
    //   if (this.selVal.toString() == '满减劵') {
    //     this.totalandless = true
    //     this.discount = false
    //   } else if (this.selVal.toString() == '打折劵') {
    //     this.totalandless = false
    //     this.discount = true
    //   }
    // },
    /* applyUser(){
           this.addCouponData.usagea=this.addCouponData.applyUser.toString();
           },
           applyShow(){
               this.addCouponData.usagea=this.addCouponData.applyShow.toString();
           },*/
    querycategory() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/coupon_Type',
          params: {}
        })
        .then(response => {
          this.categoryOption = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    queryApplyUser() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/TCK_USER',
          params: {}
        })
        .then(response => {
          this.applyUserOption = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    queryApplyShow() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/TCK_TYPE',
          params: {}
        })
        .then(response => {
          this.applyShowOption = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },


    dataSucess(message) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success'
      });
    },
    dataFail(message) {
      this.$notify({
        title: '失败',
        message: message,
        type: 'error'
      });
    },
    // uploadFile(item){
    //   if(item.file!=null&&item.file!=''){
    //   let formData = new FormData();
    //   formData.append('upFile', item.file);
    //   this.axios.post(
    //     "./coupon/coupon/template/upload/img/"+this.uuid,formData
    //   ).then(res=>{
    //     var data=res.data.data;
    //     this.list.push({'filename':data.filename,'url':data.url})
    //     this.addCouponData.backgroudImg = JSON.stringify(this.list)
    //     console.log("Carouse图片"+this.addCouponData.backgroudImg)
    //     if(this.addCouponData.backgroudImg.length>0){
    //       this.uploadImg();
    //     }
    //     console.log("File"+this.addCouponData.backgroudImg)
    //   }).catch(error => {
    //     this.dataFail("上传图片失败")
    //   });
    //   }else{
    //     this.addCouponData.backgroudImg=''
    //   }
    // },
    // uploadImg(){
    //   this.addCouponData.id=this.uuid
    //   console.log("之后id"+this.uuid)
    //   console.log("之后对象"+this.addCouponData)
    //   this.axios.request({
    //     method: "put",
    //     url: "./coupon/coupon/template/updateTemplate",
    //     headers: {
    //       "Content-Type": "application/json;charset=UTF-8"
    //     },
    //     data: replaceSpacesObj(this.addCouponData)
    //   }).then(() => {
    //   }).catch(error => {
    //     console.log(error);
    //     this.info = '上传图片后回写imgStr数据失败！';
    //     this.infoShow = true;
    //     this.dataFail("上传图片回写数据失败")
    //   });
    // },
    // imgSubmit(){
    //   if(this.showImgs.length>0) {
    //     this.showImgs.forEach(res => {
    //       this.list.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('tict'))})
    //     })
    //     this.addCouponData.backgroudImg = JSON.stringify(this.list)
    //     console.log("票面" + this.addCouponData.backgroudImg);
    //   }
    //   this.$refs.upload.submit()
    //
    //
    // },
    submit() {
      if(this.effectiveDate!=null&&this.effectiveDate!=''&&this.effectiveDate.length>=2){
        this.addCouponData.templateRule.expiration.startTime=(this.effectiveDate)[0]
        this.addCouponData.templateRule.expiration.endTime=(this.effectiveDate)[1]
      }
      console.log("对象"+this.addCouponData)
      this.$refs['addCouponData'].validate((valid) => {
        if (!valid) {
          return
        }
        this.addCouponData = replaceSpacesObj(this.addCouponData)
        this.axios.request({
          method: 'post',
          url: './coupon/coupon/template/addTemplate',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          data:replaceSpacesObj(this.addCouponData),
        }).then(response => {
          this.uuid = response.data.data
          console.log("返回对象"+this.uuid)
          this.dataSucess("新增数据成功");
          // this.imgSubmit();

          this.editOut()

        }).catch(error => {
          console.log(error)
          this.info = '票务新增失败'
          this.infoShow = true
          this.dataFail("新增数据失败");
        })
      })
    },
    closDisplay(){
      this.$emit("close");
    },
    endProcessing() {
      this.info = this.info + '新增成功,两秒后关闭'
      this.infoShow = true
      setTimeout(() => {
        this.infoShow = false
        this.$emit('editState', false)
        this.cleanHrom()
        this.info = ''
      }, 2000)
    },
    cleanHrom() {
      this.addCouponData = {

      }
    },
    editOut() {
      this.$router.push("/couponList")
    }
  }
}
</script>
<style lang="scss">
  @import "../../../styles/addTict";

</style>
